package org.answer.controller;


import org.answer.constant.MessageConstant;
import org.answer.entity.PageResult;
import org.answer.entity.QueryPageBean;
import org.answer.entity.Result;
import org.answer.pojo.CheckGroup;
import org.answer.service.BehaviorLogService;
import org.answer.service.CheckGroupService;
import org.answer.utils.BehaviorLogUtils;
import org.answer.utils.GetUserNameUtils;
import org.answer.utils.DateUtils;
import org.answer.utils.ErrorMailUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 检查组管理fasf
 */

@RestController
@RequestMapping("/checkgroup")
public class CheckGroupController {

    @Reference
    private CheckGroupService checkGroupService;

    @Reference
    private BehaviorLogService behaviorLogService;

    //log4j日志对象
    private Logger logger = ErrorMailUtils.getLogger();

    /**
     * 新增检查组
     */

    @PreAuthorize("hasAuthority('CHECKGROUP_ADD')") //  权限校验
    @RequestMapping("/add")
    public Result add(@RequestBody CheckGroup checkGroup , Integer[] checkItemsIds, HttpServletRequest request){

        List<CheckGroup> list = checkGroupService.findAll();

        try {
            for (CheckGroup group : list) {
                if (group.getCode().equals(checkGroup.getCode())){
                    return new Result(false, "当前检查组编码已占用，请输入其他编码！");
                }
            }
            checkGroupService.add(checkGroup, checkItemsIds);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.ADD_CHECKGROUP_SUCCESS
                    )
            );
        } catch (Exception e) {
            e.printStackTrace();
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.ADD_CHECKGROUP_FAIL
                    )
            );
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            //  新增失败
            return new Result(false,MessageConstant.ADD_CHECKGROUP_FAIL);
        }
        //  新增成功
        return new Result(true,MessageConstant.ADD_CHECKGROUP_SUCCESS);
    }

    //  分页查询
    @PreAuthorize("hasAuthority('CHECKGROUP_QUERY')") //  权限校验
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return checkGroupService.pageQuery(queryPageBean);
    }

    //  通过id查询检查组
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            CheckGroup checkGroup = checkGroupService.findById(id);
            return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS, checkGroup);
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
    }

    //根据检查组ID查询检查组包含的多个检查项ID
    @RequestMapping("/findCheckItemIdsByCheckGroupId")
    public Result findCheckItemIdsByCheckGroupId(Integer id) {
        try {
            List<Integer> checkitemIds = checkGroupService.findCheckItemIdsByCheckGroupId(id);
            return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, checkitemIds);//查询成功
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL);//查询失败
        }
    }


    //编辑检查组
    @PreAuthorize("hasAuthority('CHECKGROUP_EDIT')") //  权限校验
    @RequestMapping("/edit")
    public Result edit(@RequestBody CheckGroup checkGroup,Integer[] checkitemIds, HttpServletRequest request){

        List<CheckGroup> list = checkGroupService.findAll();
        Integer id = checkGroup.getId();
        String oldCode = checkGroupService.findById(id).getCode();

        try{
            if (checkGroup.getCode().equals(oldCode)){
                checkGroupService.edit(checkGroup,checkitemIds);
                behaviorLogService.add(
                        BehaviorLogUtils.getBehaviorLog(
                                GetUserNameUtils.getUsername(),
                                request.getRequestURL().toString(),
                                MessageConstant.EDIT_CHECKGROUP_SUCCESS
                        )
                );
            }else {
                for (CheckGroup group : list) {
                    if (group.getCode().equals(checkGroup.getCode())){
                        return new Result(false, "当前检查组编码已占用，请输入其他编码！");
                    }
                }
                checkGroupService.edit(checkGroup,checkitemIds);
                behaviorLogService.add(
                        BehaviorLogUtils.getBehaviorLog(
                                GetUserNameUtils.getUsername(),
                                request.getRequestURL().toString(),
                                MessageConstant.EDIT_CHECKGROUP_SUCCESS
                        )
                );
            }

        }catch (Exception e){
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            e.printStackTrace();
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.EDIT_CHECKGROUP_FAIL
                    )
            );
            return new Result(false, MessageConstant.EDIT_CHECKGROUP_FAIL);//新增失败
        }
        return new Result(true, MessageConstant.EDIT_CHECKGROUP_SUCCESS);//新增成功
    }

    //  删除
    @PreAuthorize("hasAuthority('CHECKGROUP_DELETE')") //  权限校验
    @RequestMapping("/delete")
    public Result delete(Integer id, HttpServletRequest request){

        try {
            checkGroupService.deleteById(id);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.DELETE_CHECKGROUP_SUCCESS
                    )
            );
            return new Result(true,MessageConstant.DELETE_CHECKGROUP_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.DELETE_CHECKGROUP_FAIL
                    )
            );
            return new Result(false,MessageConstant.DELETE_CHECKGROUP_FAIL);
        }
    }

    //查询全部
    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<CheckGroup> checkGroupList = checkGroupService.findAll();
            if (checkGroupList != null && checkGroupList.size() > 0) {
                Result result = new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS);
                result.setData(checkGroupList);
                return result;
            }
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
        }
        return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
    }
}
